package com.bidevalution.business.integrate;

import com.bidevalution.business.factory.StepJobJdbcFactory;
import com.bidevalution.business.function.FunctionCalculator;
import com.bidevalution.business.service.JdbcTemplateService;
import com.bidevalution.dao.entity.BeEvalutionSummary;
import com.bidevalution.dao.entity.BeSectionStep;
import com.bidevalution.dao.entity.BeSectionStepJob;
import com.bidevalution.support.util.StringUtil;
import com.google.common.collect.Maps;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.IdsUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 计算环节审核结果（少数服从多数)；一个企业中，只要有一个项未通过，则该企业未通过
 *
 * @author daizhifeng
 * @version V2.0
 * @date 2019年9月30日 下午5:07:17
 */
public class ChooseComputeResultJob implements StepJobJdbcFactory {
    private JdbcTemplateService jdbcTemplateService;

    @Override
    public Boolean execute(BeSectionStepJob beSectionStepJob, String submitCode, String expertId, String layouCode)
            throws Exception {
        String[] params = StringUtils.delimitedListToStringArray(beSectionStepJob.getJobContent(), "|");
        //c1,c2|c3 c1和c2表示计算的字段 c3表示审核结果字段
        String[] columnCodes = StringUtils.delimitedListToStringArray(params[0], ",");

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("sectionStepId", beSectionStepJob.getSectionStepId());
        paramMap.put("submitCode", submitCode);
        List<String> columnValueList;
        List<Map<String, Object>> dataList;
        //结果汇总
        Map<String, Object> resultMap = Maps.newHashMap();
        //最终结果是否通过
        String isPassed;
        //未通过原因
        StringBuilder unPassedReason = new StringBuilder();
        Map<String, Object> env;
        RowMapper<BeSectionStep> rm1 = BeanPropertyRowMapper.newInstance(BeSectionStep.class);
        //获取标段环节数据
        BeSectionStep beSectionStep = jdbcTemplateService.selectForObject(" select\n" +
                "    seq_id, section_id, step_code, step_name, parent_code, order_num, step_url, related_step_code, \n" +
                "    related_layout_code, related_column_code, related_step_id, create_time, update_time,load_function" +
                "    from be_section_step where seq_id=:sectionStepId", paramMap, rm1);
        //获取列数据
        List<Map<String, Object>> columnList = this.jdbcTemplateService.selectForList(
                "select column_code,column_text from be_section_column where section_step_id=:sectionStepId", paramMap);
        //删除已存在的汇总结果
        jdbcTemplateService.update(" DELETE FROM be_evalution_summary WHERE section_step_id=:sectionStepId and submit_code=:submitCode and is_del=0", paramMap);

        //获取评审环节的企业列表
        for (String enterpriseId : this.jdbcTemplateService.selectForList(
                "select DISTINCT enterprise_id from be_evalution_outcome where section_step_id=:sectionStepId and is_del='0'",
                paramMap, String.class)) {
            unPassedReason.delete(0, unPassedReason.length());
            isPassed = "1";
            paramMap.put("enterpriseId", enterpriseId);
            paramMap.put("layoutCode", beSectionStepJob.getLayoutCode());
            //获取评审数据
            dataList = this.jdbcTemplateService.selectForList(
                    "select c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13,c14,c15,c16,c17,c18,c19,c20 " +
                            "from be_evalution_outcome where section_step_id=:sectionStepId and is_del='0' and enterprise_id=:enterpriseId and layout_code=:layoutCode and is_finish='1'",
                    paramMap);
            //将评审结果设置为通过
            for (int i = 0; i < columnCodes.length; i++) {
                columnValueList = new ArrayList<>();
                for (Map<String, Object> data : dataList) {
                    columnValueList.add(StringUtil.toString(data.get(columnCodes[i])));
                }
                env = new HashMap<>();
                env.put("columnValues", StringUtils.collectionToDelimitedString(columnValueList, ","));
                //单列是否通过，1 表示通过，0 表示未通过
                String isSinglePassed = FunctionCalculator.computeAviator("maxFrequencyOfArray(columnValues)", env);
                resultMap.put(columnCodes[i], isSinglePassed);
                if ("0".equals(isSinglePassed)) {
                    isPassed = isSinglePassed;
                    for (Map<String, Object> column : columnList) {
                        if (columnCodes[i].equals(StringUtil.toString(column.get("column_code")))) {
                            unPassedReason.append("在【").append(beSectionStep.getStepName()).append("】中【").append(column.get("column_text")).append("】未通过评审；");
                        }
                    }
                }
            }
            //保存结果明细
            if ("1".equals(isPassed)) {
                this.jdbcTemplateService.update("update be_evalution_outcome set " + params[1] + "='1' where section_step_id=:sectionStepId and is_del='0' and enterprise_id=:enterpriseId", paramMap);
            } else {
                this.jdbcTemplateService.update("update be_evalution_outcome set " + params[1] + "='0' where section_step_id=:sectionStepId and is_del='0' and enterprise_id=:enterpriseId", paramMap);
            }
            resultMap.put(params[1],isPassed);
            //保存汇总记录
            BeEvalutionSummary beEvalutionSummary = new BeEvalutionSummary();
            BeanUtils.populate(beEvalutionSummary, resultMap);
            beEvalutionSummary.setSeqId(IdsUtil.uuid());
            beEvalutionSummary.setEnterpriseId(enterpriseId);
            beEvalutionSummary.setSectionId(beSectionStepJob.getSectionId());
            beEvalutionSummary.setSectionStepId(beSectionStepJob.getSectionStepId());
            beEvalutionSummary.setSectionStepCode(beSectionStep.getStepCode());
            beEvalutionSummary.setIsPassed(Integer.valueOf(isPassed));
            beEvalutionSummary.setUnpassedReason(unPassedReason.toString());
            beEvalutionSummary.setSubmitCode(submitCode);
            beEvalutionSummary.setCreateTime(DateUtil.now());
            beEvalutionSummary.setUpdateTime(DateUtil.now());
            jdbcTemplateService.insertBean("insert into be_evalution_summary (seq_id, section_step_id, section_step_code,section_id, submit_code, enterprise_id, c1, c2, c3, c4, c5,c6, c7, c8, c9,c10, c11, c12, c13, \n" +
                    "      c14, c15, c16, c17, c18, c19, c20, is_passed, unpassed_reason, create_time, update_time, is_del) values (:seqId, :sectionStepId, :sectionStepCode, :sectionId, \n" +
                    "      :submitCode, :enterpriseId, :c1, :c2, :c3, :c4, :c5,:c6, :c7, :c8, :c9, :c10, :c11, :c12, :c13, :c14, :c15, :c16, :c17, :c18, :c19, :c20, " +
                    "	   :isPassed, :unpassedReason, :createTime, :updateTime, 0)", beEvalutionSummary);
        }

        return true;
    }

    @Override
    public void setJdbcTemplateService(JdbcTemplateService jdbcTemplateService) {
        this.jdbcTemplateService = jdbcTemplateService;
    }

}
